<?php
namespace App\Http\Controllers\Gateway\Page;

use App\Http\Controllers\Controller;
use App\Models\PlatUser;
use App\Services\PlatUserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RechargeController extends Controller
{
    public function index(PlatUserService $userService)
    {
        $user = PlatUser::bycode(config('recharge.sandbox.mch_no'))->first();
        $payments = $userService->getPayments($user);
        $data = [];
        foreach ($payments as $payment) {
            $status = $payment->payment->status? $payment->status:0;
            if ($status) {
                $data[$payment->payment->identify] = $payment->payment->name;
            }
        }
        return view('gateway.recharge.pay', ['payments' => $data]);
    }

    public function pay(Request $request)
    {
        $mch_code = config('recharge.sandbox.mch_no');
        $app_id = config('recharge.sandbox.app_id');
        $key = config('recharge.sandbox.key');
        $data = $request->all();
        $data = array_filter($data);
        $data['mch_code'] = $mch_code;
        $data['app_id'] = $app_id;
        $data['key'] = $key;
        $data['version'] = '1.0';
        $signStr = '';
        $key = $data['key'];
        array_forget($data, 'key');
        ksort($data);
        foreach ($data as $k => $d) {
            $signStr .= $k . '=' . $d . '&';
        }
        $signStr .= $key;
        $sign = md5($signStr);
        $data['sign'] = $sign;

//        $url = route('gateway.recharge.pay') . '?' . http_build_query($data);
        $form = "<body onload='autoSubmit();'><form id='postForm' action='".route('gateway.recharge.pay')."' method='post'>";
        foreach ($data as $key => $value) {
            $form .= "<input type='hidden' value='{$value}' name='{$key}'>";
        }
        $form .= '</form></body><script type="text/javascript">function autoSubmit() { document.getElementById("postForm").submit()} </script>';
        return response($form);

    }

    public function callback(Request $request)
    {
        Log::info('异步通知:' . json_encode($request->all()));
        return response('success');
//        return json_encode($request->all());
    }

    public function query(Request $request)
    {
        $orderno = $request->input('mch_no');
        $mch_code = config('recharge.sandbox.mch_no');
        $key = config('recharge.sandbox.key');
        $queryData['version'] = '1.0';
        $queryData['mch_no'] = $orderno;
        $queryData['mch_code'] = $mch_code;
        $queryData['sign_type'] = 'md5';
        ksort($queryData);
        $signStr = '';
        foreach ($queryData as $k => $v) {
            $signStr .= "{$k}={$v}&";
        }
        $signStr .= $key;
        $queryData['sign'] = md5($signStr);
        return redirect()->to(route('gateway.recharge.query') .'?' . http_build_query($queryData));

    }
}
